package kuber

import (
	"fmt"
	"time"

	v1 "k8s.io/api/apps/v1"
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/client-go/informers"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/cache"
	"k8s.io/klog"
)

func NewInformer(kuberClient *kubernetes.Clientset, stopper chan struct{}) {
	defer close(stopper)

	informerFactory := informers.NewSharedInformerFactory(kuberClient, 30*time.Second)
	deployInformer := informerFactory.Apps().V1().Deployments()
	informer := deployInformer.Informer()
	deployLister := deployInformer.Lister()
	informer.AddEventHandler(cache.ResourceEventHandlerFuncs{
		AddFunc:    handleAdd,
		UpdateFunc: handleUpdate,
		DeleteFunc: handleDel,
	})

	// Run Informer List & Watch
	informerFactory.Start(stopper)
	// Wait for all caches of Informer to be synchronized
	informerFactory.WaitForCacheSync(stopper)
	// Get deployment in namespace 'default'
	deployments, err := deployLister.Deployments("default").List(labels.Everything())
	if err != nil {
		panic(err)
	}
	// Edit
	for k, deploy := range deployments {
		fmt.Printf("%d: %s\n", k, deploy.Name)
	}

	<-stopper
}

func handleAdd(obj interface{}) {
	deploy := obj.(*v1.Deployment)
	klog.Infof("add deploy: %s", deploy.Name)
}

func handleUpdate(old, new interface{}) {
	oldDeploy := old.(*v1.Deployment)
	newDeploy := new.(*v1.Deployment)
	klog.Infof("update deploy: %v -> %v", *oldDeploy.Spec.Replicas, *newDeploy.Spec.Replicas)
}

func handleDel(obj interface{}) {
	deploy := obj.(*v1.Deployment)
	klog.Infof("delete deploy: %s", deploy.Name)
}
